<template>
  <div class="merchant-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>商户管理</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleAdd">新增商户</el-button>
            <el-button type="success" @click="handleExport">导出商户</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="商户状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商户类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入驻时间" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="搜索关键词" prop="keyword">
          <el-input
            v-model="queryParams.keyword"
            placeholder="商户名称/联系人/手机号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计卡片 -->
      <div class="statistics-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="statistics-card">
              <template #header>
                <div class="card-header">
                  <span>总商户数</span>
                </div>
              </template>
              <div class="card-value">{{ statistics.totalMerchants }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="statistics-card">
              <template #header>
                <div class="card-header">
                  <span>待审核商户</span>
                </div>
              </template>
              <div class="card-value">{{ statistics.pendingMerchants }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="statistics-card">
              <template #header>
                <div class="card-header">
                  <span>正常营业商户</span>
                </div>
              </template>
              <div class="card-value">{{ statistics.activeMerchants }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="statistics-card">
              <template #header>
                <div class="card-header">
                  <span>本月新增商户</span>
                </div>
              </template>
              <div class="card-value">{{ statistics.newMerchants }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 商户列表 -->
      <el-table
        v-loading="loading"
        :data="merchantList"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="name" label="商户名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="type" label="商户类型" width="120">
          <template #default="{ row }">
            {{ getTypeLabel(row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="contactName" label="联系人" width="120" />
        <el-table-column prop="contactPhone" label="联系电话" width="120" />
        <el-table-column prop="address" label="商户地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="settlementAmount" label="待结算金额" width="120">
          <template #default="{ row }">
            ¥{{ row.settlementAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="入驻时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              link
              type="success"
              @click="handleEdit(row)"
              v-if="row.status !== 2"
            >
              编辑
            </el-button>
            <el-button
              link
              type="warning"
              @click="handleAudit(row)"
              v-if="row.status === 0"
            >
              审核
            </el-button>
            <el-button
              link
              type="info"
              @click="handleSettlement(row)"
              v-if="row.settlementAmount > 0"
            >
              结算
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(row)"
              v-if="row.status !== 2"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑商户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增商户' : '编辑商户'"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="商户名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商户名称" />
        </el-form-item>
        <el-form-item label="商户类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择商户类型">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="商户地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入商户地址" />
        </el-form-item>
        <el-form-item label="营业执照" prop="license">
          <el-upload
            class="license-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.license" :src="form.license" class="license" />
            <el-icon v-else class="license-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商户简介" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商户简介"
          />
        </el-form-item>
        <el-form-item label="结算账户" prop="settlementAccount">
          <el-input v-model="form.settlementAccount" placeholder="请输入结算账户" />
        </el-form-item>
        <el-form-item label="开户银行" prop="bankName">
          <el-input v-model="form.bankName" placeholder="请输入开户银行" />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankAccount">
          <el-input v-model="form.bankAccount" placeholder="请输入银行账号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="商户审核"
      width="500px"
    >
      <el-form
        ref="auditFormRef"
        :model="auditForm"
        :rules="auditRules"
        label-width="100px"
      >
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditRemark">
          <el-input
            v-model="auditForm.auditRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 结算对话框 -->
    <el-dialog
      v-model="settlementDialogVisible"
      title="商户结算"
      width="500px"
    >
      <el-form
        ref="settlementFormRef"
        :model="settlementForm"
        :rules="settlementRules"
        label-width="100px"
      >
        <el-form-item label="结算金额" prop="amount">
          <el-input-number
            v-model="settlementForm.amount"
            :min="0"
            :precision="2"
            :step="100"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="结算备注" prop="remark">
          <el-input
            v-model="settlementForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入结算备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="settlementDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSettlement">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  getMerchantList,
  getMerchantDetail,
  addMerchant,
  updateMerchant,
  deleteMerchant,
  auditMerchant,
  settlementMerchant,
  getMerchantStatistics,
  exportMerchantList
} from '@/api/merchant'

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  status: undefined,
  type: undefined,
  timeRange: [],
  keyword: ''
})

// 状态选项
const statusOptions = [
  { label: '待审核', value: 0 },
  { label: '正常营业', value: 1 },
  { label: '已拒绝', value: 2 },
  { label: '已关闭', value: 3 }
]

// 商户类型选项
const typeOptions = [
  { label: '个人商户', value: 1 },
  { label: '企业商户', value: 2 },
  { label: '连锁商户', value: 3 }
]

// 上传地址
const uploadUrl = import.meta.env.VITE_API_URL + '/upload'

// 统计数据
const statistics = ref({
  totalMerchants: 0,
  pendingMerchants: 0,
  activeMerchants: 0,
  newMerchants: 0
})

// 表格数据
const loading = ref(false)
const merchantList = ref([])
const total = ref(0)

// 新增/编辑对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = ref({
  name: '',
  type: undefined,
  contactName: '',
  contactPhone: '',
  address: '',
  license: '',
  description: '',
  settlementAccount: '',
  bankName: '',
  bankAccount: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商户名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择商户类型', trigger: 'change' }
  ],
  contactName: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入商户地址', trigger: 'blur' }
  ],
  license: [
    { required: true, message: '请上传营业执照', trigger: 'change' }
  ],
  settlementAccount: [
    { required: true, message: '请输入结算账户', trigger: 'blur' }
  ],
  bankName: [
    { required: true, message: '请输入开户银行', trigger: 'blur' }
  ],
  bankAccount: [
    { required: true, message: '请输入银行账号', trigger: 'blur' }
  ]
}

// 审核对话框
const auditDialogVisible = ref(false)
const auditFormRef = ref(null)
const auditForm = ref({
  id: undefined,
  status: 1,
  auditRemark: ''
})

// 审核表单验证规则
const auditRules = {
  status: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ],
  auditRemark: [
    { required: true, message: '请输入审核意见', trigger: 'blur' }
  ]
}

// 结算对话框
const settlementDialogVisible = ref(false)
const settlementFormRef = ref(null)
const settlementForm = ref({
  id: undefined,
  amount: 0,
  remark: ''
})

// 结算表单验证规则
const settlementRules = {
  amount: [
    { required: true, message: '请输入结算金额', trigger: 'blur' }
  ],
  remark: [
    { required: true, message: '请输入结算备注', trigger: 'blur' }
  ]
}

// 获取状态标签
const getStatusTag = (status) => {
  const map = {
    0: 'warning',
    1: 'success',
    2: 'danger',
    3: 'info'
  }
  return map[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const item = statusOptions.find(item => item.value === status)
  return item ? item.label : status
}

// 获取商户类型标签文本
const getTypeLabel = (type) => {
  const item = typeOptions.find(item => item.value === type)
  return item ? item.label : type
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const res = await getMerchantStatistics()
    statistics.value = res.data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getMerchantList(queryParams.value)
    merchantList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取商户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 重置按钮点击
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    status: undefined,
    type: undefined,
    timeRange: [],
    keyword: ''
  }
  handleQuery()
}

// 新增按钮点击
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    name: '',
    type: undefined,
    contactName: '',
    contactPhone: '',
    address: '',
    license: '',
    description: '',
    settlementAccount: '',
    bankName: '',
    bankAccount: ''
  }
  dialogVisible.value = true
}

// 编辑按钮点击
const handleEdit = async (row) => {
  try {
    const res = await getMerchantDetail(row.id)
    dialogType.value = 'edit'
    form.value = {
      id: row.id,
      ...res.data
    }
    dialogVisible.value = true
  } catch (error) {
    console.error('获取商户详情失败:', error)
    ElMessage.error('获取商户详情失败')
  }
}

// 查看按钮点击
const handleView = async (row) => {
  try {
    const res = await getMerchantDetail(row.id)
    // TODO: 实现查看详情功能
  } catch (error) {
    console.error('获取商户详情失败:', error)
    ElMessage.error('获取商户详情失败')
  }
}

// 审核按钮点击
const handleAudit = (row) => {
  auditForm.value = {
    id: row.id,
    status: 1,
    auditRemark: ''
  }
  auditDialogVisible.value = true
}

// 结算按钮点击
const handleSettlement = (row) => {
  settlementForm.value = {
    id: row.id,
    amount: row.settlementAmount,
    remark: ''
  }
  settlementDialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addMerchant(form.value)
          ElMessage.success('新增成功')
        } else {
          await updateMerchant(form.value)
          ElMessage.success('编辑成功')
        }
        dialogVisible.value = false
        handleQuery()
      } catch (error) {
        console.error(dialogType.value === 'add' ? '新增失败:' : '编辑失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '新增失败' : '编辑失败')
      }
    }
  })
}

// 提交审核
const submitAudit = async () => {
  if (!auditFormRef.value) return
  
  await auditFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await auditMerchant(auditForm.value)
        ElMessage.success('审核成功')
        auditDialogVisible.value = false
        handleQuery()
      } catch (error) {
        console.error('审核失败:', error)
        ElMessage.error('审核失败')
      }
    }
  })
}

// 提交结算
const submitSettlement = async () => {
  if (!settlementFormRef.value) return
  
  await settlementFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await settlementMerchant(settlementForm.value)
        ElMessage.success('结算成功')
        settlementDialogVisible.value = false
        handleQuery()
      } catch (error) {
        console.error('结算失败:', error)
        ElMessage.error('结算失败')
      }
    }
  })
}

// 删除按钮点击
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该商户吗？', '提示', {
      type: 'warning'
    })
    
    await deleteMerchant(row.id)
    ElMessage.success('删除成功')
    handleQuery()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 导出按钮点击
const handleExport = async () => {
  try {
    await exportMerchantList(queryParams.value)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    form.value.license = res.data.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error('上传失败')
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

onMounted(() => {
  getStatistics()
  handleQuery()
})
</script>

<style lang="scss" scoped>
.merchant-container {
  padding: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .statistics-cards {
    margin-bottom: 20px;
    
    .statistics-card {
      .card-header {
        font-size: 14px;
        color: #606266;
      }
      
      .card-value {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        text-align: center;
        padding: 10px 0;
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .dialog-footer {
    text-align: right;
  }
  
  .license-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      
      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }
  
  .license-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 200px;
    text-align: center;
    line-height: 200px;
  }
  
  .license {
    width: 200px;
    height: 200px;
    display: block;
    object-fit: cover;
  }
}
</style> 